package com.oswift.cms.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import com.oswift.cms.dao.AreaDao;
import com.oswift.cms.dao.ChannelDao;
import com.oswift.cms.dao.CompanyDao;
import com.oswift.cms.dao.ReceptionPageUrlDao;
import com.oswift.cms.dao.UserGroupDao;
import com.oswift.cms.dao.WebConfigDao;
import com.oswift.cms.entity.AreaBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CompanyBean;
import com.oswift.cms.entity.CompanyIndustryBean;
import com.oswift.cms.entity.CompanyPropertieBean;
import com.oswift.cms.entity.CompanyScaleBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.ReceptionPageUrlBean;
import com.oswift.cms.entity.UserGroupBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.entity.reception.WebConfig;
import com.oswift.cms.service.ICompanyService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.system.cache.ReceptionPageUrlManager;
import com.oswift.cms.system.cache.WebConfigManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.ReceptionConstant;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;
import com.oswift.utils.file.FileUtil;

/**
 *
 * 公司表的各种操作类
 *
 * @author zhuou
 * @version C03 Nov 12, 2012
 * @since OSwift GPM V1.0
 */
public class CompanyServiceImpl implements ICompanyService
{
    /**
     * CompanyDao对象
     */
    private CompanyDao companyDao;

    /**
     * AreaDao对象
     */
    private AreaDao areaDao;

    /**
     * ChannelDaoImpl对象注入
     */
    private ChannelDao channelDao;

    /**
     * UserGroupDao对象注入
     */
    private UserGroupDao userGroupDao;

    /**
     * WebConfigDao对象注入
     */
    private WebConfigDao webConfigDao;

    /**
     * OtherPageDao对象注入
     */
    private ReceptionPageUrlDao receptionPageUrlDao;

    /**
     *
     * 添加一条公司记录
     *
     * @author zhuou
     * @param companyBean
     *            公司记录
     * @return boolean
     * @throws PlatException
     *             CMS公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean save(CompanyBean companyBean) throws PlatException
    {
        int rows = companyDao.add(companyBean);
        if (rows <= 0 || companyBean.getCompanyId() <= 0)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 预置6个板块栏目
        // 文章
        ChannelBean articleBean = new ChannelBean();
        articleBean.setChannelName(Field.InitName.ARTICLE);
        articleBean.setCompanyId(companyBean.getCompanyId());
        articleBean.setParentId(Field.PARENT_ID);
        articleBean.setDescription(Field.InitName.DESCRIPTION);
        articleBean.setCategory(Field.ChannelCategory.DEFAULT);
        articleBean.setNickName(Field.InitName.ARTICLE_DEFAULT_NICKNAME);

        DictionaryBean bean1 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ARTICLE_KEY);
        articleBean.setForums(bean1.getFieldValue());
        boolean isSuccess = initChannel(articleBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 图片
        ChannelBean picBean = new ChannelBean();
        picBean.setChannelName(Field.InitName.PIC);
        picBean.setCompanyId(companyBean.getCompanyId());
        picBean.setParentId(Field.PARENT_ID);
        picBean.setDescription(Field.InitName.DESCRIPTION);
        picBean.setCategory(Field.ChannelCategory.DEFAULT);
        picBean.setNickName(Field.InitName.PIC_DEFAULT_NICKNAME);

        DictionaryBean bean2 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_PICURL_KEY);
        picBean.setForums(bean2.getFieldValue());
        isSuccess = initChannel(picBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 下载
        ChannelBean downloadBean = new ChannelBean();
        downloadBean.setChannelName(Field.InitName.DOWNLOAD);
        downloadBean.setCompanyId(companyBean.getCompanyId());
        downloadBean.setParentId(Field.PARENT_ID);
        downloadBean.setDescription(Field.InitName.DESCRIPTION);
        downloadBean.setCategory(Field.ChannelCategory.DEFAULT);
        downloadBean.setNickName(Field.InitName.DOWNLOAD_DEFAULT_NICKNAME);

        DictionaryBean bean3 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_DOWNLOAD_KEY);
        downloadBean.setForums(bean3.getFieldValue());
        isSuccess = initChannel(downloadBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 公告
        ChannelBean announceBean = new ChannelBean();
        announceBean.setChannelName(Field.InitName.ANNOUNCE);
        announceBean.setCompanyId(companyBean.getCompanyId());
        announceBean.setParentId(Field.PARENT_ID);
        announceBean.setDescription(Field.InitName.DESCRIPTION);
        announceBean.setCategory(Field.ChannelCategory.DEFAULT);
        announceBean.setNickName(Field.InitName.ANNOUNCE_DEFAULT_NICKNAME);

        DictionaryBean bean4 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ANNOUNCE_KEY);
        announceBean.setForums(bean4.getFieldValue());
        isSuccess = initChannel(announceBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 留言
        ChannelBean guestBookBean = new ChannelBean();
        guestBookBean.setChannelName(Field.InitName.GUESTBOOK);
        guestBookBean.setCompanyId(companyBean.getCompanyId());
        guestBookBean.setParentId(Field.PARENT_ID);
        guestBookBean.setDescription(Field.InitName.DESCRIPTION);
        guestBookBean.setCategory(Field.ChannelCategory.DEFAULT);
        guestBookBean.setNickName(Field.InitName.GUESTBOOK_DEFAULT_NICKNAME);

        DictionaryBean bean5 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_GUESTBOOK_KEY);
        guestBookBean.setForums(bean5.getFieldValue());
        isSuccess = initChannel(guestBookBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 友情链接
        ChannelBean friendSiteBean = new ChannelBean();
        friendSiteBean.setChannelName(Field.InitName.FRIENDSITE);
        friendSiteBean.setCompanyId(companyBean.getCompanyId());
        friendSiteBean.setParentId(Field.PARENT_ID);
        friendSiteBean.setDescription(Field.InitName.DESCRIPTION);
        friendSiteBean.setCategory(Field.ChannelCategory.DEFAULT);
        friendSiteBean.setNickName(Field.InitName.FRIENDSITE_DEFAULT_NICKNAME);

        DictionaryBean bean6 = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_FRIENDSITE_KEY);
        friendSiteBean.setForums(bean6.getFieldValue());
        isSuccess = initChannel(friendSiteBean);
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        // 内置用户组
        UserGroupBean groupBean = new UserGroupBean();
        groupBean.setCompanyId(companyBean.getCompanyId());
        groupBean.setGroupName(Field.InitName.GROUPNAME);
        groupBean.setDescription(Field.InitName.GROUPNAME);
        groupBean.setGroupType(Field.MemberGroupType.BUILT_IN);
        isSuccess = userGroupDao.add(groupBean) > 0 ? true : false;
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }
        return true;
    }

    /**
     *
     * 新增站点信息
     *
     * @author zhuou
     * @param webBean
     *            站点bean
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean saveWebConfig(WebConfigBean webBean) throws PlatException
    {
        // 新增公司站点信息
        boolean isSuccess = webConfigDao.add(webBean) > 0 ? true : false;
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        String siteUrl = webBean.getSiteUrl();
        if (siteUrl.indexOf(Field.COMMA) != -1)
        {
            String[] urls = siteUrl.split(Field.COMMA);
            WebConfig newBean = null;
            for (String s : urls)
            {
                // 为了多次生产新的对象
                newBean = new WebConfig();
                newBean.setCompanyId(webBean.getCompanyId());
                newBean.setCopyright(webBean.getCopyright());
                newBean.setErrorPagePath(webBean.getErrorPagePath());
                newBean.setLogoUrl(webBean.getLogoUrl());
                newBean.setMetaDescription(webBean.getMetaDescription());
                newBean.setMetaKeywords(webBean.getMetaKeywords());
                newBean.setSiteName(webBean.getSiteName());
                newBean.setSiteUrl(s.trim());
                WebConfigManager.setValue(newBean);
            }
        }
        else
        {
            // 将公司和站点信息存入缓存
            WebConfig bean = new WebConfig();
            bean.setCompanyId(webBean.getCompanyId());
            bean.setCopyright(webBean.getCopyright());
            bean.setErrorPagePath(webBean.getErrorPagePath());
            bean.setLogoUrl(webBean.getLogoUrl());
            bean.setMetaDescription(webBean.getMetaDescription());
            bean.setMetaKeywords(webBean.getMetaKeywords());
            bean.setSiteName(webBean.getSiteName());
            bean.setSiteUrl(siteUrl.trim());
            WebConfigManager.setValue(bean);
        }

        return true;
    }

    /**
     *
     * 获取公司的属性信息
     *
     * @author zhuou
     * @return map
     * @throws PlatException
     *             CMS公共异常
     */
    public Map<String, Object> getCompanyOtherInfo() throws PlatException
    {
        Map<String, Object> map = new HashMap<String, Object>();

        List<CompanyIndustryBean> industrys = companyDao.getIndustry();
        List<CompanyPropertieBean> properties = companyDao.getPropertie();
        List<CompanyScaleBean> scales = companyDao.getScaleBean();
        List<AreaBean> area = areaDao.getArea(Field.Area.PROVINCE);
        map.put("industrys", industrys);
        map.put("properties", properties);
        map.put("scales", scales);
        map.put("areas", area);

        return map;
    }

    /**
     *
     * 获取公司列表
     *
     * @author zhuou
     * @param keyword
     *            查询关键字
     * @param pageNum
     *            页码
     * @param pageRecordNum
     *            每页显示记录数
     * @return PageBean
     * @throws PlatException
     *             CMS公共异常
     */
    public PageBean<CompanyBean> getCompanyList(String keyword, int pageNum,
            int pageRecordNum, int companyId) throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        return companyDao.getCompanyList(keyword, rowNum, pageRecordNum,
                companyId);
    }

    /**
     *
     * 获取公司详情
     *
     * @author zhuou
     * @param companyId
     *            id
     * @return CompanyBean
     * @throws PlatException
     *             CMS公共异常
     */
    public Map<String, Object> getCompanyDetail(int companyId)
        throws PlatException
    {
        Map<String, Object> map = getCompanyOtherInfo();
        CompanyBean bean = companyDao.selectOne(companyId);
        map.put("detail", bean);

        return map;
    }

    /**
     *
     * 获取公司详情,用于显示详情
     *
     * @author zhuou
     * @param companyId
     * @return CompanyBean
     * @throws PlatException
     *             CMS公共异常
     */
    public CompanyBean companyDetail(int companyId) throws PlatException
    {
        return companyDao.selectOne(companyId);
    }

    /**
     *
     * 根据公司Id获取网站配置信息
     *
     * @author zhuou
     * @param siteId
     *            站点Id
     * @return WebConfigBean
     * @throws PlatException
     *             公共异常
     */
    public WebConfigBean webConfigDetail(int siteId) throws PlatException
    {
        return webConfigDao.selectOne(siteId);
    }

    /**
     *
     * 修改公司信息
     *
     * @author zhuou
     * @param companyBean
     * @return
     * @throws PlatException
     *             CMS公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean update(CompanyBean companyBean) throws PlatException
    {
        CompanyBean oldBean = companyDao.selectOne(companyBean.getCompanyId());
        if (null == oldBean)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR,
                    "The company has been deleted.");
        }

        boolean isSuccess = companyDao.update(companyBean) > 0 ? true : false;
        if (!isSuccess)
        {
            return false;
        }
        return true;
    }

    /**
     *
     * 修改站点信息
     *
     * @author zhuou
     * @param companyBean
     * @return
     * @throws PlatException
     *             CMS公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean updateWebConfig(WebConfigBean webBean) throws PlatException
    {
        WebConfigBean oldBean = webConfigDao.selectOne(webBean.getSiteId());
        if (null == oldBean)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR,
                    "The WebConfig has been deleted.");
        }

        boolean isSuccess = webConfigDao.update(webBean) > 0 ? true : false;
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }

        String oldSiteUrl = oldBean.getSiteUrl();
        // 修改缓存数据（如果网站改变，缓存key也改变）
        // 先删除
        if (oldSiteUrl.indexOf(Field.COMMA) != -1)
        {
            String[] urls = oldSiteUrl.split(Field.COMMA);
            for (String s : urls)
            {
                WebConfigManager.remove(s);
            }
        }
        else
        {
            WebConfigManager.remove(oldSiteUrl);
        }

        // 公司id不容许修改
        webBean.setCompanyId(oldBean.getCompanyId());
        String siteUrl = webBean.getSiteUrl();
        if (siteUrl.indexOf(Field.COMMA) != -1)
        {
            String[] urls = siteUrl.split(Field.COMMA);
            WebConfig newBean = null;
            for (String s : urls)
            {
                // 为了多次生产新的对象
                newBean = new WebConfig();
                newBean.setSiteId(webBean.getSiteId());
                newBean.setCompanyId(webBean.getCompanyId());
                newBean.setCopyright(webBean.getCopyright());
                newBean.setErrorPagePath(webBean.getErrorPagePath());
                newBean.setLogoUrl(webBean.getLogoUrl());
                newBean.setMetaDescription(webBean.getMetaDescription());
                newBean.setMetaKeywords(webBean.getMetaKeywords());
                newBean.setSiteName(webBean.getSiteName());
                newBean.setSiteUrl(s.trim());
                WebConfigManager.setValue(newBean);
            }
        }
        else
        {
            // 将公司和站点信息存入缓存
            WebConfig bean = new WebConfig();
            bean.setSiteId(webBean.getSiteId());
            bean.setCompanyId(webBean.getCompanyId());
            bean.setCopyright(webBean.getCopyright());
            bean.setErrorPagePath(webBean.getErrorPagePath());
            bean.setLogoUrl(webBean.getLogoUrl());
            bean.setMetaDescription(webBean.getMetaDescription());
            bean.setMetaKeywords(webBean.getMetaKeywords());
            bean.setSiteName(webBean.getSiteName());
            bean.setSiteUrl(siteUrl.trim());
            WebConfigManager.setValue(bean);
        }
        return true;
    }

    /**
     *
     * 删除某个站点信息
     *
     * @author zhuou
     * @param siteId
     *            站点id
     * @webPath 工程绝对路径
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean delWebConfig(int siteId, String webPath)
        throws PlatException
    {
        WebConfigBean oldBean = webConfigDao.selectOne(siteId);
        if (null == oldBean)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR,
                    "The WebConfig has been deleted.");
        }

        // 删除数据库信息
        boolean isSuccess = webConfigDao.delete(siteId) > 0 ? true : false;
        if (!isSuccess)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR,
                    "The WebConfig deleted is failure.");
        }

        // 将前台页面url配置查询出来
        List<ReceptionPageUrlBean> receptionPageUrlBeans = receptionPageUrlDao
                .getReceptionPageUrlListBySiteId(siteId);

        // 删除功能表数据
        // 删除t_cms_receptionpageurl表数据
        receptionPageUrlDao.delAllBySiteId(siteId);

        // 删除前台页面
        StringBuffer pagePath = new StringBuffer(webPath);
        pagePath.append(ReceptionConstant.FILE_SEPARATOR);
        pagePath.append(ReceptionConstant.USERFILE);
        pagePath.append(ReceptionConstant.FILE_SEPARATOR);
        pagePath.append(ReceptionConstant.USERFILENAME);
        pagePath.append(siteId);
        String path = FileUtil.getPathForFileName(pagePath.toString());
        if (!StringUtil.isEmpty(path))
        {
            File file = new File(path);
            isSuccess = FileUtil.deleteFile(file);
            if (!isSuccess)
            {
                throw new PlatException(ErrorCode.COMMON_FILE_DEL_FAIL,
                        "The File deleted is failure.");
            }
        }

        String oldSiteUrl = oldBean.getSiteUrl();
        // 修改缓存数据（如果网站改变，缓存key也改变）
        // 先删除
        if (oldSiteUrl.indexOf(Field.COMMA) != -1)
        {
            String[] urls = oldSiteUrl.split(Field.COMMA);
            for (String s : urls)
            {
                WebConfigManager.remove(s);
            }
        }
        else
        {
            WebConfigManager.remove(oldSiteUrl);
        }

        // 删除前台页面url配置缓存数据
        if (null != receptionPageUrlBeans)
        {
            for (ReceptionPageUrlBean item : receptionPageUrlBeans)
            {
                ReceptionPageUrlManager.remove(item.getSiteId(), item
                        .getUrlType(), item.getNickName());
            }
        }

        return true;
    }

    /**
     *
     * 预置每个单位的6个栏目
     *
     * @author zhuou
     * @param channelBean
     *            栏目Bean
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean initChannel(ChannelBean channelBean) throws PlatException
    {
        // 计算出channelId
        int channelId = Field.DEFAULT_CHANNELID;
        ChannelBean top1Bean = channelDao.getTop1Channel();
        if (null != top1Bean)
        {
            channelId = top1Bean.getChannelId() + 1;
        }
        channelBean.setChannelId(channelId);

        return channelDao.saveContainCh(channelBean) > 0 ? true : false;
    }

    /**
     *
     * 根据公司id获取公司列表，如果company=-1获取所有公司，如果>-1则只获取此公司的信息
     *
     * @author zhuou
     * @param companyId
     *            公司id
     * @return List<CompanyBean>
     * @throws PlatException
     *             CMS公共异常
     */
    public List<CompanyBean> getCompanysbyCId(int companyId)
        throws PlatException
    {
        return companyDao.getCompanysbyCId(companyId);
    }

    /**
     *
     * 获取网站配置信息列表
     *
     * @author zhuou
     * @param keyword
     *            查询关键字
     * @param pageNum
     *            页码
     * @param pageRecordNum
     *            每页显示记录数
     * @return PageBean
     * @throws PlatException
     *             CMS公共异常
     */
    public PageBean<WebConfigBean> getWebConfigList(String keyword,
            int pageNum, int pageRecordNum, int companyId) throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        return webConfigDao.getWebConfigList(keyword, rowNum, pageRecordNum,
                companyId);
    }

    public CompanyDao getCompanyDao()
    {
        return companyDao;
    }

    public void setCompanyDao(CompanyDao companyDao)
    {
        this.companyDao = companyDao;
    }

    public AreaDao getAreaDao()
    {
        return areaDao;
    }

    public void setAreaDao(AreaDao areaDao)
    {
        this.areaDao = areaDao;
    }

    public ChannelDao getChannelDao()
    {
        return channelDao;
    }

    public void setChannelDao(ChannelDao channelDao)
    {
        this.channelDao = channelDao;
    }

    public void setUserGroupDao(UserGroupDao userGroupDao)
    {
        this.userGroupDao = userGroupDao;
    }

    public void setWebConfigDao(WebConfigDao webConfigDao)
    {
        this.webConfigDao = webConfigDao;
    }

    public void setReceptionPageUrlDao(ReceptionPageUrlDao receptionPageUrlDao)
    {
        this.receptionPageUrlDao = receptionPageUrlDao;
    }
}
